package com.bsi.limiter.handler;

import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import org.springframework.cloud.gateway.support.TimeoutException;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName BlockRequestHandlerEx
 * @Author LiuSong
 * @Date 2020/8/3 10:08
 * @Version 1.0
 * @Description 配置异常处理器的信息打印
 */
public class BlockRequestHandlerEX implements BlockRequestHandler {
    @Override
    public Mono<ServerResponse> handleRequest(ServerWebExchange serverWebExchange, Throwable throwable) {
        throwable.printStackTrace();
        Map map = new HashMap<>();
        map.put("code", 001);
        map.put("message", "对不起,接口限流了");
        return ServerResponse.status(HttpStatus.OK).
                contentType(MediaType.APPLICATION_JSON_UTF8).body(BodyInserters.fromObject(map));
    }

    @PostConstruct
    public void initBlockHandler() {
        GatewayCallbackManager.setBlockHandler(this);
    }
}
